package middleware

import (
	"encoding/json"
	"log"
	"net/http"
	"runtime/debug"
)

// RecoveryMiddleware 创建一个恢复中间件，捕获处理函数中的异常，防止服务崩溃
func RecoveryMiddleware() func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			defer func() {
				if err := recover(); err != nil {
					// 记录堆栈信息
					log.Printf("服务异常: %v\n%s", err, debug.Stack())

					// 返回500错误
					w.Header().Set("Content-Type", "application/json")
					w.WriteHeader(http.StatusInternalServerError)

					// 构造错误响应
					response := map[string]string{
						"status":  "error",
						"message": "系统错误，请稍后再试",
					}

					// 输出错误信息
					json.NewEncoder(w).Encode(response)
				}
			}()

			// 继续处理请求
			next.ServeHTTP(w, r)
		})
	}
}
